<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>操作元素的属性值</title>
    <style>
      #box1 {
        width: 200px;
        height: 30px;
        background-color: pink;
        margin-bottom: 40px;
      }

      #box2 {
        width: 200px;
        height: 30px;
        background-color: skyblue;
        margin-bottom: 5px;
      }
      .box2-btn {
        margin-bottom: 40px;
      }

      #box3 {
        width: 200px;
        height: 30px;
        background-color: #ffd700;
        margin-bottom: 5px;
      }

      button {
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <!-- 1、获取元素的属性值 -->
      <div id="box1" data-index="1"></div>

      <!-- 2、设置元素的属性值 -->
      <div id="box2" class="my-box2" data-name="myBox2"></div>
      <div class="box2-btn">
        <button>设置内置属性值</button>
        <button>设置自定义属性值</button>
      </div>

      <!-- 3、移除元素的属性 -->
      <div id="box3" class="my-box3" data-index="3"></div>
      <div class="box3-btn">
        <button id="box3Btn">移除元素属性</button>
      </div>
    </div>

    <script>
      // 1、获取元素的属性值
      var box1 = document.querySelector('#box1');
      console.log('获取内置属性值--', box1.id);
      console.log('获取自定义属性值--', box1.getAttribute('data-index'));

      // 2、设置元素的属性值（注意：class 比较特殊）
      var box2 = document.querySelector('#box2');
      var box2Btns = document.querySelector('.box2-btn').querySelectorAll('button');
      box2Btns[0].onclick = function () {
        box2.id = 'box222';
        box2.className = 'my-box222';
      };
      box2Btns[1].onclick = function () {
        box2.setAttribute('data-name', 'myBox222');
        box2.setAttribute('class', 'my-box222333'); // 注意：class 比较特殊
      };

      // 3、移除元素属性
      var box3 = document.querySelector('#box3');
      var box3Btn = document.getElementById('box3Btn');
      box3Btn.onclick = function () {
        box3.removeAttribute('class');
        box3.removeAttribute('data-index');
      };
    </script>
  </body>
</html>
